package main

import (
	"context"
	"fmt"
	"gitee.com/zackeus/go-boot/freeswitch/esl"
	"gitee.com/zackeus/go-zero/core/logx"
	"sync"
	"time"
)

func initEsl() (*esl.InboundEngine, error) {
	if err := logx.SetUp(logx.LogConf{Mode: "console", Encoding: "plain"}); err != nil {
		return nil, err
	}

	// Connect to FreeSWITCH
	inbound := esl.NewInbound("192.168.137.71:8021")
	if err := inbound.Start(); err != nil {
		return nil, err
	}
	return inbound, nil
}

func main() {
	inbound, err := initEsl()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer inbound.Close()

	// 设置要模拟并发数
	concurrent := 1000

	// 创建等待组，以便在所有goroutines完成时等待
	var wg sync.WaitGroup

	// 创建一个通道，用于收集每个goroutine的结果
	results := make(chan time.Duration, concurrent)

	// 启动多个goroutines模拟并发用户
	for i := 0; i < concurrent; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			startTime := time.Now()

			ctx := context.Background()
			_, err := inbound.GetGlobalVar(ctx, "domain")
			if err != nil {
				fmt.Println(err)
				return
			}

			duration := time.Since(startTime)
			results <- duration
		}()
	}

	// 等待所有goroutines完成
	wg.Wait()

	// 计算总的请求时间和吞吐量
	close(results)
	var totalTime time.Duration
	var totalRequestsCompleted int
	for duration := range results {
		totalTime += duration
		totalRequestsCompleted++
	}
	averageResponseTime := totalTime / time.Duration(totalRequestsCompleted)
	requestsPerSecond := float64(totalRequestsCompleted) / totalTime.Seconds()

	// 打印结果
	fmt.Printf("Total Requests: %d\n", totalRequestsCompleted)
	fmt.Printf("Total Time: %d\n", totalTime.Milliseconds())
	fmt.Printf("Average Response Time: %s\n", averageResponseTime)
	fmt.Printf("Requests Per Second: %.2f\n", requestsPerSecond)
}
